I have a first table called "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....
I need to join just one to get the news_name from the joined table so the base select is
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.
I just need one to capture the news_name from the events table.
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 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.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.