开发者

Help with MySQL query combining 2 tables with LIKE AND OR statement?

开发者 https://www.devze.com 2023-03-05 09:44 出处:网络
I\'m trying to get results for articles that have a title or subcategory name similar to the request.

I'm trying to get results for articles that have a title or subcategory name similar to the request.

Table 1
Subcategory_ID Subcategory_Name

Table 2
Article_ID   Title  Subcategory_ID

Now I need to fetch articles from table 2 where title or subcategory_names match what we're looking for.

Here is what I have, but I can't come up with the rest

 SELECT table1.*, table2.* FROM table1,table2 WHERE table2.title = '%keyword%'

and the rest I mess up...

What is the solution?开发者_开发问答


Try this:

SELECT t2.Title, t1.Subcategory_Name
FROM Table2 t2 JOIN Table1 t1
ON t2.Subcategory_ID = t1.Subcategory_ID
WHERE t2.title LIKE '%keyword%' OR t1.Subcategory_Name LIKE '%keyword%' 


SELECT table1.*, table2.* FROM table1, table2 
  WHERE table1.Subcategory_ID=table2.Subcategory_ID 
  AND (table2.title LIKE '%keyword%' OR table1.Subcategory_Name LIKE '%keyword%')

With MySQL INNER JOIN it is implicit if you use "table1.Subcategory_ID=table2.Subcategory_ID" in the WHERE clause.


May be by

select t1.*,t2.* 
  from `table2` t2 join `table1` t1 
  on t1.Subcategory_ID = t2.Subcategory_ID 
  where t2.title LIKE '%keyword%' or t1.Subcategory_Name LIKE '%keyword%'


SELECT table1.*, table2.* FROM table1 INNER JOIN table2 USING (Subcategory_id) 
  WHERE table2.title LIKE '%keyword%'

You can replace USING (Subcategory_id) with ON (table1.subcategory_id = table2.subcategory_id).

For more explanation see MySQL Tutorial - Join.

0

精彩评论

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