How to select from table A one row and table B multi rows?

不打扰是莪最后的温柔 提交于 2019-12-08 11:17:25

问题


I have two tables.

Pages

+-----------+----------+------------+
| ID        | title    |    URL     |
+-----------+----------+------------+
| 1         | test     | test.html  |
| 2         | test2    | test2.html |
+-----------+----------+------------+

Files

+-----------+----------+------------+
| ID        | page_id  |    name    |
+-----------+----------+------------+
| 10        |    1     |   a.jpg    |
| 11        |    1     |   b.jpg    |
| 12        |    2     |   c.jpg    |
+-----------+----------+------------+

How to select from PAGES one row and FILES multi rows??

My query as:

select * from pages,files WHERE (pages.id = page_id) AND  (url='$url')

The output for above query:

test
a.jpg

The output I need:

test
a.jpg
b.jpg

回答1:


This is more of a sql question than anything to do with specifically PHP.
I think this is what you want, but I'm not sure with your wording.

SELECT pages.title, files.name 
FROM pages 
INNER JOIN files ON pages.id = files.page_id
WHERE (pages.url='$url')
GROUP BY files.name;



回答2:


Something like this

SELECT 
    Files.Name 
FROM Files 
INNER JOIN Pages ON Files.page_id = Pages.Id
WHERE Pages.url = '$url'

UNION ALL 

SELECT 
    Pages.title
FROM Pages 
WHERE Pages.url = '$url'


来源:https://stackoverflow.com/questions/29905891/how-to-select-from-table-a-one-row-and-table-b-multi-rows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!