如何从第一个表返回所有列,从第二个表返回仅一列

问题描述 投票:0回答:2

我有一张名为“购买”的第一张桌子

news_series, transaction_id, owner_id, amount

我有另一个名为“事件”的表

news_name, news_id, series_id, news_description

我遇到的问题是,如果我这样做

purchases.news_series joins to events.series_id

问题是系列ID可以有多个事件....

我需要加入一个才能从连接表中获取news_name,因此基本选择是

Select * from purchases where owner_id=29

140, asldkfj_sdfx34, 29, 40

然后我添加联接表

Select * 
from purchases 
LEFT JOIN events on purchases.news_series=events.series_id 
where owner_id=29

140, asldkfj_sdfx34, 29, 40,"THIS EVENT", 606, 140, "MY FIRST EVENT"
140, asldkfj_sdfx34, 29, 40,"THIS EVENT", 607, 140, "MY FIRST EVENT"

我最终返回了几行...我只需要一个从事件表中捕获new_name。

任何建议总是赞赏。我在这里尝试了一些解决方案无济于事,所以是的,我在发布前已经看了。

谢谢

mysql sql mysqli left-join
2个回答
2
投票

我只需要一个从事件表中捕获news_name。

这就是我要做的:

购买表:

+-------------+----------------+----------+--------+
| news_series | transaction_id | owner_id | amount |
+-------------+----------------+----------+--------+
| 140         | asldkfj_sdfx34 | 29       | 40     |
+-------------+----------------+----------+--------+

活动表:

+------------+---------+-----------+------------------+
| news_name  | news_id | series_id | news_description |
+------------+---------+-----------+------------------+
| THIS EVENT | 606     | 140       | MY FIRST EVENT   |
+------------+---------+-----------+------------------+
| THIS EVENT | 607     | 140       | MY FIRST EVENT   |
+------------+---------+-----------+------------------+

SELECT DISTINCT只是你想要从连接表中的一列:

SELECT DISTINCT p.*, e.news_name
FROM Purchases p
LEFT JOIN Events e ON p.news_series = e.series_id
WHERE p.owner_id = 29

enter image description here


如果你不SELECT DISTINCT,这就是你得到两行的原因。

enter image description here


测试:

;WITH Purchases (news_series, transaction_id, owner_id, amount) AS (
    SELECT '140','asldkfj_sdfx34','29','40'
), Events (news_name,news_id,series_id,news_description) AS (
    SELECT 'THIS EVENT','606','140','MY FIRST EVENT' UNION ALL
    SELECT 'THIS EVENT','607','140','MY FIRST EVENT' )

SELECT DISTINCT p.*, e.news_name
FROM Purchases p
LEFT JOIN Events e ON p.news_series = e.series_id
WHERE p.owner_id = 29

0
投票

我可能会建议:

Select p.*,
       (select e.news_name
        from events e
        where p.news_series = e.series_id 
        limit 1
       )
from purchases  p
where owner_id = 29;

保证每次购买返回一行。

© www.soinside.com 2019 - 2024. All rights reserved.