I have two tables:
employees:
id, CMS_user_id, practice_group_id, ...
and
users:
id, level, ...
I want to select all employees where practice_group_id is 2 but only if the respective user has a level of 1 according to the users table. I researched and I have a feeling it has something to do with the UNION keyword eventually, but I can't quite figure it out.
In "human language", the query would be like this:
"select all from employees where practice_group_id is 2 and then check the CMS_user_id from the employee and check in the table users whether the respective user with the id that equals CMS_user_id has a level of 1"
A JOIN will match the corresponding rows between two tables. Then, filtering can be done using WHERE.
For example:
select e.*
from employees e
join users u on u.id = e.CMS_user_id
where e.practice_group = 2 and u.level = 1
Related
I am having 3 tables (c19 , c19b2, g26) in a database
I want to write a SQL Query to search and display all fields of the matched record.
I am using following query:
$query = "SELECT * FROM c19,c19b2,g26 WHERE armyno LIKE '%$searchTerm%'";
But it only works for table c19,
Data from the other 2 tables is not fetched.Each table has a field armyno
Please help me with this
Thank you.
Alright, you are not looking for a JOIN, but a UNION.
SELECT * FROM c19 WHERE armyno LIKE '%$searchTerm%'
UNION
SELECT * FROM c19b2 WHERE armyno LIKE '%$searchTerm%'
UNION
SELECT * FROM g26 WHERE armyno LIKE '%$searchTerm%'
That will let you query all three tables at the same time.
Which DB are you using? This would have worked in SQL Server. However, notice you are doing a cross join of every record to every record... usually you only want to match some records by restriction of a matching key, for example:
select
*
from a
left join b on b.somekey = a.somekey
left join c on c.someotherkey = b.someotherkey
In SQL server you can just say *, but I'm taking it that in your DB engine that didn't work, so try specifying which table. This may in some environments require aliasing as well:
select
a.*,
b.*,
c.*
from tableA as a
left join tableB as b on b.somekey = a.somekey
left join tableC as c on c.someotherkey = b.someotherkey
Generally, you should see the columns from the first table, followed by the columns from the second table, followed by columns from the third table for a given row. If you wanted to get all columns from all tables, but separately, then that would be 3 separate selects.
Lastly, if all 3 tables have "armyno" then I'd expect it to throw an ambiguous field error. In such case you'd want to specify which table's "armyno" field to filter on.
I need to report the number of records that match each of several criteria. For example, how many customers live in each state. I know I can accomplish this through a series of MySQL SELECT statements, but that seems cumbersome and produces a ton of (unnecessary?) MySQL calls.
Can you tell me a better method to use? Can I query the database with one SELECT statement and then use PHP to filter the results to variables?
I'd suggest creating a view for this task just to hide the complexity of the query. Also, in the event that your table schema changes, it is likely that you are still going to want to retrieve this same information from the database. You'd be able to change the view in one place, instead of having to change the queries in, possibly, multiple places to satisfy your schema changes.
I'll just show you the queries, though, since you'd need to know how to do that to create a view anyways.
Sticking with your example of customers living in each state, let's pretend you also want statistics on how many customers share the same last name.
I've setup a mock structure of what your database might be like at this SqlFiddle.
Customers with Same LastName
The following query might be used to get the number of customers with the same last name:
SELECT
LastName AS "Value",
COUNT(*) AS "Count"
FROM Customers
GROUP BY
LastName;
Customers in Same State
Similarly, the customers in the same state might be retrieved with a query as follows:
SELECT
S.Name AS "Value",
COUNT(*) AS "Count"
FROM Customers AS C
INNER JOIN CustomerAddresses AS CA ON C.Id = CA.CustomerId
INNER JOIN Addresses AS A ON CA.AddressId = A.Id
INNER JOIN States AS S ON A.State = S.Id
GROUP BY
A.State;
Getting Your Desired Format
The format that you want is an aggregation of these two queries. You want both returned as a single result set. So, let's workout a schema for the returned table:
ResultType - This will hold a value that corresponds to the type of result. i.e. "State"
Value - This will hold the value of the aggregated column. i.e. "Florida"
Count - This will hold the total number of records that match the aggregated column.
So, now that we have a format, let's create a query that uses our two queries from above, and puts them into this format.
First, I add a new field to each of the above queries: ResultType
For example:
"LastName" AS "ResultType"
Now, I combine my queries into a single query using the UNION ALL statement:
SELECT * FROM (
/* LastName query */
SELECT
"LastName" AS "ResultType",
LastName AS "Value",
COUNT(*) AS "Count"
FROM Customers
GROUP BY
LastName
UNION ALL
/* States query */
SELECT
"State" AS "ResultType",
S.Name AS "Value",
COUNT(*) AS "Count"
FROM Customers AS C
INNER JOIN CustomerAddresses AS CA ON C.Id = CA.CustomerId
INNER JOIN Addresses AS A ON CA.AddressId = A.Id
INNER JOIN States AS S ON A.State = S.Id
GROUP BY
A.State
) AS A
In my SqlFiddle above, this produces an output like:
RESULTTYPE VALUE COUNT
=================================
LastName Jetson 1
LastName Johnson 2
LastName Milton 1
State Florida 2
State Georgia 1
State Utah 1
As you can see, this could get quite complex, so you might consider looking into placing this into a view. Then, you'd be able to query your view, as if it was the table above (ResultType, Value, and Count). That would also allow you to filter on it.
create select query make number of aliens of table and make your related columns aliens which is you want to use.
lest see sample example
SELECT a.id AS id
FROM Table1 AS a
WHERE ...
UNION ALL
SELECT b.name AS name
FROM Table2 AS b
WHERE ...
ORDER BY (a or b) ...
i have two tables in my database. table A is USERS and table B is relations, and the following are their columns
USERS(username, avatar, specialty) and RELATIONS(username1, username2, reldir)
RELATIONS stores the relationship between users, that is if, username1 is following username2, reldir = F, and if they are both following each other, reldir=FB and vice versa, this part has worked very well but
i need to query these tables so that i return a list of users from USERS which for example user A doesnt follow but have the same specialty as A...
i tried this, but its not working well ...
$spec = the specialty of user A
SELECT a.username, a.avatar, a.specialty FROM users a, relations b WHERE a.username!=b.username2 AND (b.reldir!='F' OR b.reldir!='FB') AND a.speciality ='$spec'
the query to me seems logically correct but i could be wrong. i need help
You need to add some keys for your tables, because you have two different tables and they doesn't linked.
For example, table USERS:
id (as primary_key), username, avatar, specialty
Table RELATIONS:
user_id, username2, reldir
user_id - it is field "id" from table USERS (instead your "username1")
Then you will be able create a query like this:
SELECT a.*
FROM users a, relations b
WHERE a.id = b.users_id
AND (b.reldir != 'F' OR b.reldir != 'FB')
AND a.speciality = '$spec'
ps: if I understood your question in the right way)
How can I run a select query on a multivalue attribute? Does mysql have a function do select certain data from a multivalue field? Much help is appreciated. Here's a sample of the problem:
Table
userid groups
-------------------
2 2,3,5
4 1
9 2,5,10
datatype is char(250) for groups
I want to do a query to select all userids that belong to group 5, in this example it would be userid 2 and 9. So:
userid
------
2
9
Any way to go about it with a mysql query? or with php/mysql?
In case the groups datatype is SET
You can use
SELECT * FROM users WHERE FIND_IN_SET('5', groups);
UPDATE
In case of char or varchar. You can use this
SELECT * FROM users
WHERE
groups LIKE '5,%'
OR groups LIKE '%,5'
OR groups LIKE '%,5,%'
OR groups = '5'
This is ugly, but if you want to do it completely in MySQL, you could do:
SELECT *
FROM users
WHERE groups LIKE '%,5,%'
OR groups = '5'
OR groups LIKE '%,5'
OR groups LIKE '5,%'
You'd be better off having a separate table with one group per row and a reference back to the user. You could do a join with a much simpler condition with that schema.
SELECT users.*
FROM users
INNER JOIN users_groups ON (users.user_id = users_groups.group_id)
WHERE users_groups.group_id = 5
I'm new to these types of MySQL Queries.
Basically, I have two tables in a MySQL Database. One is called groupmembers and the other is called users
groupmembers contains rows with two columns, a groupid and a userid
users contains rows with also two columns, a userid and a username
I am trying to write a query that searches the groupmembers table with rows with a groupid of 15, but where the userid in groupmembers links with the one in users and searches that one too.
For example:
SELECT * FROM groupmembers WHERE groupid = 15 (something to find the user row by using the userids) AND users.username = '%testquery%'
If you need any more information on this, just let me know because I am bad at explaining things!
Try:
SELECT * FROM groupmembers g INNER JOIN users u ON
g.userid = u.userid WHERE g.groupid = 15 and u.username LIKE '%testquery%'
ORDER BY u.userid