简体   繁体   English

如何根据同一表中另一列的值获取列的所有值?

[英]How to fetch all values of a column based on value of another column in same table?

I got the following structure:我得到了以下结构:

admin_id  ||  country_id 
---------------------------------
 1              2      
 5              1
 1              2
 2              3
 5              62
 1              1
 3              62

How to fetch all values by taking the $_SESSION['admin']['id'] , finding the country_id of that admin and getting all other admin_id and country_id that are the same of the session admin?如何通过获取$_SESSION['admin']['id']获取所有值,找到该管理员的 country_id 并获取与会话管理员相同的所有其他 admin_id 和 country_id?

So, lets say the currently logged in admin has id = 5 , that means the admin_id: 5 has two country_id: 1 and 62. I want to take all rows that have country_id: 1 and 62.所以,假设当前登录的 admin 有id = 5 ,这意味着 admin_id: 5 有两个 country_id: 1 和 62。我想获取所有具有 country_id: 1 和 62 的行。

It should return this:它应该返回这个:

admin_id || country_id 
------------------------        
 5              1  
 5              62
 1              1
 3              62

How can I do this in one sql query?如何在一个 sql 查询中执行此操作?

You can use a where clause for filtering on the admin_id or the country_id :您可以使用where子句过滤admin_idcountry_id

select t.*
from t
where t.admin_id = 5 or
      t.country_id in (select t2.country_id from t t2 where t2.admin_id = 5);
SELECT t1.*
FROM table t1
JOIN table t2 USING (country_id)
WHERE t2.admin_id = 5

fiddle 小提琴

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 MYSQL查询-一种基于同一表中另一列中的DISTINCT值从一列返回所有值的简单方法? - MYSQL query - simple way to return all values from one column based on a DISTINCT value in another column in the same table? 如何搜索表中是否存在多个值并且在另一列中都具有相同的值? - How to search if multiple values exist in the table and all have the same value in another column? 根据Laravel中另一列(同表)的值自动更新列(7) - Update column automatically based on value of another column (same table) in Laravel (7) 如何基于函数调用更新表的所有行中的列,而该函数具有同一列中的现有值 - How to Update a column in all rows of a table based on a function call with existing value in that same column 如何在一行中获取具有相同 id 但在另一列中具有不同值的数据并在 php 中的表中显示一个月 - How to fetch data with same id in a row but different value in another column and display one month into table in php 将列值复制到同一表中的另一列 - Copy column values to another column in the same table 如何根据 Laravel 8 中同一表中的另一列在列中存储值 - How to store value in column depending on another column in same table in Laravel 8 从一个表中取出一列,在另一个表中搜索相同的列值,最后从第三个表中取出并显示数据 - Fetch a column from one table, search the same column value in another table and finally fetch and display data from the third table 根据另一个列值的顺序为表中的所有行编号 - Number all rows in table based on order of another column value 根据同表 sql 和 php 另一列的更改更新表中的列值 - Update column values in table based on changes on another column same table sql and php
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM