I have 2 tables :
sellers
id|name
locations
id|seller_id|name
Now I want to get sellers and join locations and combine attributes from both tables in where clause.
Initial query is :
SELECT
sellers.id
FROM sellers
JOIN locations.seller_id = sellers.id
I must add one more part because I don't want duplicated data :
SELECT
sellers.id
FROM sellers
JOIN locations on locations.seller_id = sellers.id
WHERE (
SELECT id from locations
WHERE locations.seller_id = sellers.id
LIMIT 1
)
Now I can do the following
SELECT
sellers.id
FROM sellers
JOIN locations on locations.seller_id = sellers.id
WHERE (
SELECT id from locations
WHERE locations.seller_id = sellers.id
LIMIT 1
)
AND (
sellers.name = 'test'
OR
locations.name = 'test'
)
Any ideas?
UPDATED :
example with data :
sellers
id|name
1|test
2|test2
locations
id|seller_id|name
1|1|test3
2|2|test4
3|2|test
4|2|test
result should be
[1, 2] but with my query it is [1]
If you make your SQL simpler, the answer becomes simpler.
SELECT DISTINCT
sellers.*
FROM sellers
INNER JOIN locations on locations.seller_id = sellers.id
WHERE
sellers.name = 'test'
OR
locations.name = 'test'
You can use Group By
with Having
:
SELECT sellers.id,
sellers.name,
SUM(locations.name = 'test') AS has_test_location
FROM sellers
INNER JOIN locations on locations.seller_id = sellers.id
GROUP BY sellers.id, sellers.name
HAVING sellers.name = 'test' OR
has_test_location
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.