如何在第二个查询中使用MySQL值?

时间:2012-01-13 11:08:01

标签: mysql union

我该怎么做:

SELECT Board_id FROM topic WHERE Value1='".$value2."' UNION SELECT Name FROM Boards WHERE Id=Board_id

我应该使用UNION吗?或者我应该使用两个不同的查询?什么更好?

5 个答案:

答案 0 :(得分:0)


SELECT t.Board_id, B.Name FROM topic t
left join Boards B ON (B.id = t.Board_id)
where t.SELECT Board_id FROM topic = $value1

答案 1 :(得分:0)

SELECT Name FROM Boards WHERE Id = (SELECT Board_id FROM topic WHERE Value1='".$value2."')

答案 2 :(得分:0)

使用联接:

select name, board_id from boards b inner join topic t on t.board_id=b.id
where t.value1='VALUE1'

请参阅W3学校的SQL连接教程:http://www.w3schools.com/sql/sql_join.asp

注意,如果您使用的是PHP,则代码存在SQL注入的风险:http://en.wikipedia.org/wiki/SQL_injection

有很多方法可以防止这种情况发生:

$sql = "SELECT board_id, name from boards b inner join topic t on " .
   " t.board_id=b.id " .
   " where t.value1='" . mysql_real_escape_string($value2) . "'";

最好还是使用参数化查询,但这取决于你是使用PHP的MySQL还是MySQLi库。

答案 3 :(得分:0)

我想你想要:

SELECT Name 
FROM Boards 
WHERE Id
    = ( SELECT Board_id 
         FROM topic 
         WHERE Value1 =  $value2
      ) 

答案 4 :(得分:0)

我建议你使用以下ID加入Boards表:

SELECT topic.Board_id, Boards.name 
FROM topic 
LEFT JOIN Boards 
ON topic.Board_id = Boards.id 
WHERE topic.Value1='".$value2."'