更正mysql查询以查询一个表,并为另一个表查询提供信息

时间:2014-03-25 05:01:00

标签: php mysql sql

我有两个单独的表,我需要同时查询这些表以获取要显示的正确信息。这些表是成员和帖子。通过html表单,用户输入成员表的条件,然后我需要使用所有这些特定成员的主索引来查找这些成员提交的所有帖子,然后对posts表结果进行排序。结果将是两个表中的行的混合。两个表都有一个名为'id'的主索引。到目前为止,我想出的是:

$sql_get_posts = mysqli_query($link, "(SELECT id, username FROM members WHERE active='y' AND gender='M' AND city='Yuma' AND state='Arizona') UNION (SELECT * FROM posts WHERE member_id='id' AND active='y' ORDER BY list_weight DESC)") or die(mysqli_error($link));

我得到的错误是“使用的SELECT语句具有不同的列数”。

然后我需要循环查看两个表的返回结果,以填充用户看到的内容:

<?php
   while ($row = mysqli_fetch_array($sql_get_posts)) {
     $post_id = $row['id']; //This should be the post primary index named 'id', not the member primary index also name 'id'
     $member_id = $row['member_id']; //This is the member_id row in the post table referencing this particular member who wrote this post 
     $member_username = $row['username']; //This is a row stored in the member table
     $title = $row['title']; //This is a row stored in post table
     ******//and on and on getting rows from only the post table
   }

编辑我的SQL表:

CREATE TABLE IF NOT EXISTS `members` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `username` varchar(20) NOT NULL,
 `age` varchar(3) NOT NULL,
 `gender` varchar(1) NOT NULL,
 `city` varchar(20) NOT NULL,
 `state` varchar(50) NOT NULL,
 `active` enum('y','n') NOT NULL DEFAULT 'y',
 `created_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;


CREATE TABLE IF NOT EXISTS `posts` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `member_id` int(11) NOT NULL,
  `title` text NOT NULL,
  `comments` enum('y','n') NOT NULL DEFAULT 'y',
  `post_date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `list_weight` double NOT NULL,
  `active` enum('y','n') NOT NULL DEFAULT 'y',
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=47 ;

3 个答案:

答案 0 :(得分:0)

UNION中的SELECT语句必须具有相同的列数。列还必须具有类似的数据类型。此外,每个SELECT语句中的列必须具有相同的顺序。

但是您在第一次查询中只选择了2列,并且&#34; *&#34;对于第二个选择查询

答案 1 :(得分:0)

使用连接

SELECT m.id, m.username,p.* FROM members m JOIN posts p on m.active='y' AND m.gender='M' AND m.city='Yuma' AND m.state='Arizona' and p.member_id='id' AND p.active='y' ORDER BY p.list_weight DESC

或者您可以使用

SELECT m.id, m.username,p.* FROM members m,posts p where m.active='y' AND m.gender='M' AND m.city='Yuma' AND m.state='Arizona' and p.member_id='id' AND p.active='y' ORDER BY p.list_weight DESC

答案 2 :(得分:0)

使用join而不是union,union假定您组合的表是相似的,而join合并两个表的列。

类似的东西:

SELECT members.id, members.username, posts.*
FROM members
INNER JOIN posts
ON members.id = posts.member_id
WHERE members.active='y' AND members.gender='M' AND members.city='Yuma' AND members.state='Arizona'
ORDER BY posts.list_weight DESC