[英]match id of one table to user_id of another table to fetch records in mysql
I have two tables,lets say x and y. 我有两张桌子,请说x和y。 i am using two queries to fetch x table data by one query and fetch all rows from y table matching x's id with y's UserId
我正在使用两个查询通过一个查询来获取x表数据,并从与x的id和y的UserId匹配的y表中获取所有行
here is my mysql 这是我的mysql
include 'config.php'; 包括'config.php';
$sql1= mysql_query("select FirstName,MiddleName,LastName,Gender,Location,Email,Mobile from personaldetails limit 1");
$sql2 = mysql_query("select BookTilte,BookGenre,BookWriter,BookDescription from bookdetails where personaldetails.Id = bookdetails.UserId ")
Please also suggest some alternative solution if it's wrong 如果错误,也请提出一些替代解决方案
you can use from INNER JOIN in these cases 在这种情况下,您可以使用INNER JOIN
SELECT FirstName,MiddleName,LastName,Gender,Location,Email,Mobile,BookTilte,BookGenre,BookWriter,BookDescription FROM `personaldetails` as `PD` INNER JOIN `bookdetails` AS `BD` ON `PD`.`Id` = `BD`.`UserId`
Note: mysql_query is deprecated and you should use mysqli functions 注意:不建议使用mysql_query,而应使用mysqli函数
Try with below query 尝试以下查询
$sql1= mysql_query("select a.FirstName,a.MiddleName,a.LastName,a.Gender,a.Location,a.Email,a.Mobile,b.BookTilte,b.BookGenre,b.BookWriter,b.BookDescription from personaldetails as a join bookdetails as b on a.Id=b.UserId limit 1");
Join will combine the two tables.
联接将合并两个表。
a and b are aliases of two tables.
a和b是两个表的别名。 By using aliases, we can specify which field select from which table.
通过使用别名,我们可以指定从哪个表中选择哪个字段。
a.Id=b.UserId is for specify the primary key and reference key
a.Id = b.UserId用于指定主键和参考键
It s not wrong, it could be the right thing to do sometimes. 没错,有时候做对也许是正确的事。
An alternative solution could be 替代解决方案可能是
$str = <<<MARKER
SELECT FirstName,MiddleName,LastName,Gender,Location,Email,Mobile
FROM personaldetails
INNER JOIN bookdetails ON (personaldetails.Id = bookdetails.UserId)
ORDER BY personaldetails.Id
MARKER;
$sql1= mysql_query($query);
Notes, 笔记,
you don't need the limit anymore as it would return only the first row. 您不再需要该限制,因为它将仅返回第一行。
For each bookdetails
, you ll find a personaldetails
line ( personaldetails
will be duplicated), 对于每个
bookdetails
,您都会找到一个personaldetails
行( personaldetails
将重复),
I added an ORDER BY
clause to show you. 我添加了
ORDER BY
子句向您展示。
you should reference primary keys, or indexed columns, or add new indexes 您应该引用主键或索引列,或添加新索引
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.