Get all fields from table and mark some under specific condition - mysql

I have two database tables:
First table is named FIELDS and has following two columns:
FIELD_ID whose data-type is int
FIELD_NAME whose data-type is varchar
Second table is named SHIPPINGS and has following two columns:
FIELD_ID whose data-type is int
SHIPPING_ID whose data-type is int
I need to retrieve all field names, and mark those which have certain SHIPPING_ID set in table SHIPPINGS.
Example:
If I will choose SHIPPING_ID = 3, I'd like to receive the following structure:
s_firstname true
b_lastname false
s_lastname false
How do I do this? I have tried the following SQL query:
SELECT pf.field_name, ps.shipping_id, IF(ps.shipping_id = 3, "true", "false") AS status
FROM `fields` AS pf LEFT JOIN `shippings` AS ps
ON ps.shipping_id = 3
But it returns true for all fields.
What did I do wrong?

You can use aggregation:
select f.*, (s.field_id is not null) as has_3
from fields f left join
shippings s
on f.field_id = s.field_id and s.shipping_id = 3;
Note: This interprets the results as wanting a boolean value. If you want a string, then use a case expression:
select f.*,
(case when s.field_id is not null then 'true' else 'false end) as has_3

Related

Filter Left Join Unique Value

I have two tables and need to choose only the unique value from the left join.
This is the code I tested with.
First table - answered (Field Name - src)
Second Table - noanswered (Field Name - src2)
SELECT DISTINCT src2
FROM answerd
RIGHT noanswered ON answerd.src = noanswered.src2
WHERE answerd.src IS Not NULL;
SELECT DISTINCT *
FROM answered
WHERE NOT EXISTS ( SELECT NULL
FROM noanswered
WHERE answered.src = noanswered.src2 );

Update values of one column with multiple values

There is a table and that table has a column with a name country and I need to change values at that column in one query instead of multiple queries.
In this query, I change any value with Egypt to be 1
UPDATE subscribers
SET country = 1 WHERE country = 'Egypt';
in this query, I change any value with Qatar to be 2
UPDATE subscribers
SET country = 2 WHERE country = 'Qatar';
Any help to make these two queries in one?
Consider:
UPDATE subscribers SET country =
CASE
WHEN country = "Egypt" THEN 1
WHEN country = "Qatar" THEN 2
ELSE country
END
;
Now imagine doing that expression for many more countries. Instead join to a table that 'maps' data association (a master table of country names). Join on CountryName fields and update destination table CountryName field with ID from 'mapping' table. Convert to number type field. Or play it safe and update to another field and when all looks good, delete the original field.
You can use a case expression in MySQL:
UPDATE subscribers
SET country = (CASE WHEN country = 'Egypt' THEN 1 ELSE 2 END)
WHERE country IN ('Egypt', 'Qatar');
However, I would recommend using a derived table:
UPDATE subscribers s JOIN
(SELECT 'Egypt' as country, '1' as new_country UNION ALL
SELECT 'Qatar' as country, '2' as new_country
) x
USING (country)
SET s.country = x.new_country;

compare data between two tables and populate a flag column in 1st table with 'Y'if exist else 'N"

I have two tables, if data exist in 1st table then populate flag column with 'Y' if does not populate with 'N', I am comparing only 3 columns, one is number, 2nd is name and 3rd column is datetime. However my busines rule case statment always returns 'Y"
Table 1 (staging table, type1)
column1: number, data (123, 456,756)
column2: name, date('Mike', 'Dray','John')
column3: datetime. data('2018-12-03 14:00:52.000','2018-12-03 14:00:52.000','2018-12-03 14:00:52.000')
Table2 (landing table, type2)
column1 number, data (123, 456,756, 890)
column2: name, date('Mike', 'Dray','John','Chris')
column3: datetime. data('2018-12-03 14:00:52.000','2018-12-03 14:00:52.000','2018-12-03 14:00:52.000','2018-09-20 10:31:39.000')
column4: flagcolumn, data('Y','Y','Y','N')
so last column 4 in table 2 should populate to y/n based if data is in table 1 or not.
I have wrote query as like:
WITH CDE AS (
SELECT T1.number,T1.name,T1.Bdatetime,
FROM dbo.db.table T1)
,CDE1 AS (
SELECT CDE.*,BUS_RULE_valid = (
select case
when EXISTS (
SELECT number, name, datetime
FROM dbo.db.table T1
WHERE number IN
(SELECT number
FROM dbo.db.table2)
AND name
(SELECT name FROM dbo.db.t2)
AND datetime IN
(SELECT datetime FROM dbo.db.t2))
THEN 'Y'
ELSE 'N'
END)
FROM CDE
)
SELECT * FROM CDE1
You're checking if the three values individually exist in the other table, which is likely almost always the case. Looks like you need to check for the combined value, which would look something like the query below.
I took the libery of removing the with part, since that didn't seem necessary here. But you could keep it as well, the solutions would be the same (apart from the table alias used).
SELECT
T1.number_col,
T1.name_col,
T1.datetime_col,
CASE WHEN EXISTS (
SELECT 'x' FROM dbo.db.table2 T2
WHERE
t2.number_col = T1.number_col AND
t2.name_col = T1.name_col AND
t2.datetime_col = T1.datetime_col)
THEN 'Y'
ELSE 'N'
END AS BUS_RULE_valid
FROM dbo.db.table1 T1

My SQL: Add if condition in where statement?

I want to select all customers or one customer from same SP. Right now we are mantaining two SPs to get these details:
i.e. To get all customers:
select id, name from customers
and to get one customer:
select id, name from customers
where id=id_from_input
To make them common, i thought of pasing id_from_input as null to get all customers. I tried several ways to make a conditional where statement in my sql that would work with this plan, but nothing is working. For example:
select id, name from customers
where if(id_from_input <> null) id=id_from_input; end if
gives me syntax error.
How can I make a where clause that returns all rows when id_from_input is null, the matching row otherwise?
The expression x <> null is never true; you can only use is null, or is not null, to test for null. Correcting your attempt gives:
select id, name from customers
where id_from_input is null or id = id_from_input
Or for something more terse (and IMHO elegant):
select id, name from customers
where id = coalesce(id_from_input, id)
Use CASE Statement to achieve your result :
SELECT id, name FROM customers WHERE id = CASE WHEN ISNULL(id_from_input,'')
<> '' THEN id_from_input ELSE id END
Try to use or:
select id, name
from customers
where id_from_input is null or id = id_from_input
if id_from_input is null then or clause will not be calculated.
Try this query
select id, name from customers where
CASE WHEN id_from_input<>null THEN id=id_from_input
ELSE id END

JOIN data from same table

I have a table containing the names, emails, positions, etc of a students, as well as their "status" (which can be one of Y or N.) I want to write a query that counts the number of each type of position, as well as the number of Y AND the number of N within each type using JOIN. (That is, it would be a table with three columns: Position, StatusIsYes, and StatusIsNo.)
I have already done this using the CASE clause the following way, but I can't figure out how to do it using the JOIN clause.
SELECT position,
COUNT(CASE WHEN status = 'Y' THEN 1 ELSE NULL END) AS StatusIsYes,
COUNT(CASE WHEN status = 'N' THEN 1 ELSE NULL END) AS StatusIsNo
FROM
students GROUP BY crd
I appreciate any suggestions!
EDIT: I know it can be done without using JOIN, but I want to know how it is possible to do it with a JOIN.
You don't need a join:
SELECT
position,
SUM(status = 'Y') AS StatusIsYes,
SUM(status = 'N') AS StatusIsNo
FROM students
GROUP BY position
Note the rather funky dispensing of the CASE, because in mysql (only) true is 1 and false is 0, so sum() of a condition counts how many times it is true :)
You can use SELF JOIN in the case when you want to fetch records from same table.
For ex:
Table Name: employee
Fields : EmpId,EmpName,ManagerId
Now if you want to get the details of Empolyees who are in Manager Position for that we need to write query like this:
SELECT e1.EmpId, e1.EmpName FROM EmployeeDetails e1, EmployeeDetails e2 where e1.EmpId=e2.ManagerId;
Hope it will help you.
Fro more information please check this link.
Try ::
SELECT
position,
COUNT(status = 'Y' ) AS StatusIsYes,
COUNT(status = 'N' ) AS StatusIsNo
FROM
students GROUP BY POSITION