[英]How to return all columns from 1st table and only 1 column from 2nd table
I have a first table called "purchases"我有一张名为“purchases”的表
news_series, transaction_id, owner_id, amount
I have another table called "Events"我有另一个名为“事件”的表
news_name, news_id, series_id, news_description
The issue that I'm running into is that if I do我遇到的问题是,如果我这样做
purchases.news_series joins to events.series_id
The issues is that there can be multiple events with the series id....问题是系列 id 可以有多个事件....
I need to join just one to get the news_name from the joined table so the base select is我只需要加入一个即可从连接表中获取news_name ,因此基本选择是
Select * from purchases where owner_id=29
140, asldkfj_sdfx34, 29, 40
then I add the joined table然后我添加连接表
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"
and I end up with a few rows returned...I just need one to capture the new_name from the events table.我最终返回了几行......我只需要一个来从事件表中捕获 new_name 。
I just need one to capture the news_name from the events table.我只需要一个来从事件表中捕获 news_name 。
This is what I would do:这就是我会做的:
PURCHASES TABLE:采购表:
+-------------+----------------+----------+--------+
| news_series | transaction_id | owner_id | amount |
+-------------+----------------+----------+--------+
| 140 | asldkfj_sdfx34 | 29 | 40 |
+-------------+----------------+----------+--------+
EVENTS TABLE:事件表:
+------------+---------+-----------+------------------+
| news_name | news_id | series_id | news_description |
+------------+---------+-----------+------------------+
| THIS EVENT | 606 | 140 | MY FIRST EVENT |
+------------+---------+-----------+------------------+
| THIS EVENT | 607 | 140 | MY FIRST EVENT |
+------------+---------+-----------+------------------+
SELECT DISTINCT
just the one column you want from the joined table: 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
If you do not SELECT DISTINCT
, this is why you are getting two rows.如果你没有SELECT DISTINCT
,这就是你得到两行的原因。
Test:测试:
;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
Might I suggest:我可以建议:
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;
This is guaranteed to return one row per purchase.这保证每次购买返回一行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.