我有一张名为“购买”的第一张表
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。
任何建议总是受到赞赏。我在这里尝试了一些解决方案无济于事,所以是的,我在发布前已经看了。
由于
答案 0 :(得分: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
如果你没有SELECT DISTINCT
,这就是你要获得两行的原因。
测试:
;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
答案 1 :(得分: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;
保证每次购买返回一行。