开发者

MySQL search based search

In MySQL I have two tables, say Customers and Orders, looking like this:

[Customers]
'ID'    'Name'    'Phone_nr'
开发者_如何学Python 1       Ted       12345
 2       Anna      54321
 3       Anna      98765

[Orders]
'ID'    'Customer_ID'   'Price'
 1       2               100
 2       2               50
 3       1               70
 4       2               120
 5       3               80

Now i want to search for orders ID where 'Customers.Name = Anna' and Price > 60... I was hoping i do something like:

SELECT 'ID' FROM 'Orders' WHERE 'Customer_ID' = (SELECT 'ID' FROM 'Customers' WHERE 'Name' = 'Anna') AND 'Price' > 60

I want this to return Order IDs 1, 4 and 5.

So basically, make a search based on ID numbers found by a search in an other table...

This will likely be done on large tables with maybe 1k results for "Anna", i would also be open to other ways of structuring the tables, especially if it requires less of the server, but i still have items in one table that are linked to items in an other table, and i need to filter both.

Hope i'm being clear about this, and thanks for your time.


SELECT Orders.Id
FROM Orders
INNER JOIN Customers ON Customers.Id = Orders.Customer_ID
WHERE Customers.'Name' = 'Anna' AND Orders.'Price' > 60


SELECT o.id 
FROM   orders o, customers c 
WHERE  o.Customer_ID = c.ID AND 
       o.Price > 60         AND
       c.Name = 'Anna';


SELECT ID FROM Orders o
JOIN Customers c ON c.ID = o.Customer_ID
WHERE c.Name = 'Anna' AND Price > 60

Side note: I wouldn't recommend to use uppercase characters for database table and column names.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜