我想从两个用户名表中找出我的用户名,其中用户名已经停留在table2中。这意味着如果任何表中的用户名匹配,我的查询将收集其用户ID。
table 1: username --- userid > john --- 100
table 2: username --- userid > colin --- 101
我在这里看了很多文章,我无法理解我该怎么做。
现在想想:我需要约翰的uesrid,
所以我试过了:
$username = "john";
$q = "SELECT userid FROM table1,table2 WHERE table1.username = '$username' or table2.username = '$username'";
$result = mysqli_query($this->connection, $q);
答案 0 :(得分:0)
您可以选择两个userid
字段,然后查看是否设置了其中一个字段:
$username = "john";
$q = "SELECT table1.userid AS userid1,table2.userid AS userid2 FROM table1,table2 WHERE table1.username = '$username' or table2.username = '$username'";
$result = mysqli_query($this->connection, $q);
答案 1 :(得分:0)
试试这个:
$username = "john";
$q = "SELECT table1.userid FROM table1 JOIN table2 ON table1.username=table2.username WHERE table1.username = '$username'";
$result = mysqli_query($this->connection, $q);
如果加工模式(table1.username = table2.username)等于true,则JOIN将table2连接到table1,或者从table1中排除结果中的这一行。
答案 2 :(得分:0)
根据我的理解,您想检查一个表中是否已存在该名称。
这是简单的PHP代码:
<?php
session_start();
include 'db_connect.php';
$check_1 = mysqli_query("SELECT * FROM Table_1 WHERE Username = '$Username'");
$check_2 = mysqli_query("SELECT * FROM Table_2 WHERE Username = '$Username'");
if(mysqli_num_rows($check_1)==0){
//Didnt exist in table 1
}
else if(mysqli_num_rows($check_2)==0){
//No result in table 2 either.
}
else{
//what you want to do if the username doesnt exist
}
让我知道它是如何为您解决的:)
答案 3 :(得分:0)
您可以使用UNION子句
$q="SELECT t1.userid FROM table1 as t1 WHERE username='$username' UNION SELECT t2.userid FROM table2 as t2 WHERE username='$username'";
答案 4 :(得分:0)
您可以使用左连接
$username = "username";
$q = "SELECT userid
FROM table1
LEFT JOIN table2 ON table1.username = table2.username
WHERE table1.username = '$username' or table2.username = '$username'";
$result = mysqli_query($this->connection, $q);