I have 2 tables : registered_students - cols: regnum AND student - cols: regnum, name
So I'm working on a query to select from both tables. It's working so far, but now I want to add a where clause to it, and it's not returning any rows. Here is the query
SELECT registered_students.regnum
, student.name
FROM registered_students
INNER JOIN student ON registered_students.regnum=student.regnum
example data:
registered_students 1).reg3030 2). reg4032
student 1).reg3030 John Doe 2).reg4032 Luke White
So I need to add a where clause like WHERE regnum LIKE 'reg4%'
You will have to specify the alias as the column has same name in both the tables, try the following query:
SELECT registered_students.regnum, student.name
FROM registered_students JOIN student ON registered_students.regnum=student.regnum
WHERE registered_students.regnum LIKE 'reg4%';
The output will also depend on the availability of data with reg4 in both the tables. You could try the following if the above does not work:
case insensitive matching, e.g. WHERE LOWER(registered_students.regnum) LIKE 'reg4%'
LEFT JOIN if you want the data from either of these tables
Update
With the updated data, it might be because of whitespace or a dot in the beginning of the value, I would try the following:
SELECT registered_students.regnum, student.name
FROM registered_students JOIN student ON TRIM(registered_students.regnum) = TRIM(student.regnum)
WHERE registered_students.regnum LIKE '%reg4%';
Related
I have these three tables:
The table "Clienti" contains the customers.
The table "Corsi" contains all the available courses
The table "corsi Fatti" contains all the Courses each client has taken.
what I would need is a query that returns each client, and what courses he attended on what date.
For that I would like to have for example a table returned with these columns:
Clienti.Nome, corsi.row1.corso, corsi.row2.corso, corsi.row3.corso,corsi.rowN.corso.
and the content of the table should be:
clienti.Nome, corsifatti.data of the matching course in the corsi table if present.
so, first column is the client name, and then there is a column for each row of the "corsi" table, and if a client has partecipated on that course then the corsifatti.data should be in that column.
Can something like this be done with a Access or Mysql Query? I have tried with inner joins but the result was not what I need.
select
Clienti.nome, Clienti.Addresse, Clienti.CAP, Clienti.Tel,
Clienti.Ansprechpartner, Clienti.Mail, Clienti.Weiteres,
CorsiFatti.Data, Corsi.Corso, Corsi.Durata
from Clienti
INNER JOIN CorsiFatti on CorsiFatti.[ID Cliente] = Clienti.ID
INNER JOIN Corsi on Corsi.ID = CorsiFatti.[ID Corso]
What you are asking is a simple inner join:
select Clienti.nome, Clienti.Addresse, Clienti.CAP,
Clienti.Tel, Clienti.Ansprechpartner, Clienti.Mail,
Clienti.Weiteres,
CorsiFatti.Data,
Corsi.Corso, Corsi.Durata
from Clienti
INNER JOIN CorsiFatti on CorsiFatti.[ID Cliente] = Clienti.ID
INNER JOIN Corsi on Corsi.ID = CorsiFatti.[ID Corso]
order by Clienti.nome, Corsi.Corso;
I think you meant yours was lacking the order by only.
I wouldn't suggest using access, but if it is access anyway, then you need to have parenthseses around all those joins (peculiar I know, but it is access).
The pivot with variable columns count is complicated. I can advice simplest solution uses JSON aggregation:
SELECT
ClienteId,
Name,
JSON_ARRAYAGG(
JSON_OBJECT("Data", Data, "Corso", Corso)
) Corsi
FROM
CorsiFatti
JOIN Corsi ON Corsi.Id = CorsiFatti.CorsoId
JOIN Clienti ON Clienti.Id = CorsiFatti.clienteId
GROUP BY
ClienteId,
Name
;
Result is row for each client contains client's data at his courses as JSON string:
+===========+=========+========================================================================================+
| ClienteId | Name | Corsi |
+===========+=========+========================================================================================+
| 1 | Mr. Fix | [{"Data": "2021-01-01", "Corso": "Corso1"}, {"Data": "2021-02-01", "Corso": "Corso3"}] |
+-----------+---------+----------------------------------------------------------------------------------------+
Here you can find SQL fiddle
I'm trying to build a database similar to the structure in the picture
I tried using this code but it doesn't seem to work.
SELECT wp_wpdatatable_4.remaining, wp_wpdatatable_7.name
FROM wp_wpdatatable_4
INNER JOIN wp_wpdatatable_7
ON wp_wpdatatable_7.name LIKE CONCAT(wp_wpdatatable_4.techsname, '%');
Can anyone help?
You are close, just interchange the field names.
You are trying to query John Smith LIKE 'John Smith CTE 555-555-5555%' which will never be true.
This will be true John Smith CTE 555-555-5555 LIKE 'John Smith%'
Here is corrected query
SELECT wp_wpdatatable_4.remaining, wp_wpdatatable_7.name
FROM wp_wpdatatable_4
INNER JOIN wp_wpdatatable_7
ON wp_wpdatatable_4.techsname LIKE CONCAT(wp_wpdatatable_7.name, ' %');
Note: added space before % to ensure word match
Update
To sum values in remaining column, use GROUP BY. Here is the updated query:
SELECT SUM(wp_wpdatatable_4.remaining) AS total_remaining, wp_wpdatatable_7.name
FROM wp_wpdatatable_4
INNER JOIN wp_wpdatatable_7
ON wp_wpdatatable_4.techsname LIKE CONCAT(wp_wpdatatable_7.name, ' %')
GROUP BY wp_wpdatatable_7.name;
Use wildcards on wp_wpdatatable_7.name:
SELECT wp_wpdatatable_4.remaining, wp_wpdatatable_7.name
FROM wp_wpdatatable_4
INNER JOIN wp_wpdatatable_7
ON wp_wpdatatable_4.techsname like '%wp_wpdatatable_7.name%'
I need to build a query with multiple JOIN, to be more especific, 2 JOINS, but it gets duplicated results, check this:
My current tables:
food_shops
id, slug, name
categories_food_shops
id, id_cat, id_food_shop
pictures_food_shops
id, pic_slug, id_food_shop
And I need to get * from food_shops, the id_cat from categories_food_shops and pic_slug from pictures_food_shops...
My current query is like this:
SELECT food_shops.id, food_shops.slug, food_shops.name,
GROUP_CONCAT(categories_food_shops.id_category) as categories,
GROUP_CONCAT(pictures_food_shops.slug) as pictures
FROM
food_shops
JOIN categories_food_shops
ON food_shops.id = categories_food_shops.id_food_shop
JOIN pictures_food_shops
ON food_shops.id = pictures_food_shops.id_food_shop
GROUP BY food_shops.slug, pictures_food_shops.id_food_shop
But since my pictures_food_shops have more results as the categories_food_shops, my result is gettin "quadruplicated":
What can I do to prevent this and get only the correct amount of categories?
Only 1 at the first row, 3 and 5 in the second one and 7,1,6 at the last one?
Thanks!
You can try this:
...
GROUP_CONCAT(DISTINCT categories_food_shops.id_category) as categories,
....
This should work for pictures also.
Here is the documentation with DISTINCT usage example.
I have a table name as "invoice" which consists of column name "CId"
I have another table name as invoiceclient_details which consists of column name "CId"
So now my question is "what query should i write so that i will get the data of greater "CId" i.e. rows of data which consists of greater "CID"
I have tried like this
SELECT
invoiceclient_details.OrganizationName,
invoiceclient_details.InvoiceNo,
invoiceclient_details.InvoiceDate,
invoiceclient_details.DeliveryNote,
invoiceclient_details.TermsofPayment,
invoiceclient_details.EsugamNo,
invoiceclient_details.OrganizationName,
invoiceclient_details.BuyerOrderNo,
invoiceclient_details.BuyDate,
invoiceclient_details.DispatchDocumentNo,
invoiceclient_details.Dated,
invoiceclient_details.DispatchThrough,
invoiceclient_details.Destination,
invoiceclient_details.TermsofDelivery,
invoiceclient_details.BuyerTin,
invoice.id,
invoice.DescriptionOfGoods,
invoice.Quantity,
invoice.PerUnitPrice,
invoice.TotalPrice,
invoice.VAT14,
invoice.VAT5,
invoice.ServiceTax,
invoice.CST
FROM invoiceclient_details,invoice
WHERE MAX(invoiceclient_details.CId) = MAX(invoice.CId);
But it is showing an error like
"misusage of group function"
Use an INNER JOIN to join the tables on the CId.
SELECT *
FROM invoice i
INNER JOIN invoiceclient_details icd ON i.CId = icd.CId
Try this
select *
from invoice,invoiceclient_details
where
invoice.CId in (Select max(invoiceclient_details.CId) from invoiceclient_details)
and
invoiceclient_details.CId in (Select max(invoiceclient_details.CId) from invoiceclient_details)
I need some help about optimal structuring of SQL query. I have model like this:
I'm trying some kind of join between tables NON_NATURAL_PERSON and NNP_NAME. Because I have many names in table NNP_NAME for one person I can't do one-to-one SELECT * from NON_NATURAL_PERSON inner join NNP_NAME etc. That way I'll get extra rows for every name one person has.
Data in tables:
How to extend this query to get rows marked red on picture shown below? My wannabe query criteria is: Always join name of typeA only if exists. If not, join name of typeB. If neither exists join name of typeC.
SELECT nnp.ID, name.NAME, name.TYPE
FROM NON_NATURAL_PERSON nnp
INNER JOIN NNP_NAME name ON (name.NON_NATURAL_PERSON = nnp.ID)
If type is spelled exactly as it's written (typeA, typeB, typeC) then you can use MIN() function:
SELECT NON_NATURAL_PERSON, MIN(type) AS min_type
FROM NNP_NAME
GROUP BY NON_NATURAL_PERSON
if you also want the username you can use this query:
SELECT
n1.NON_NATURAL_PERSON AS ID,
n1.Name,
n1.Type
FROM
NNP_NAME n1 LEFT JOIN NNP_NAME n2
ON n1.NON_NATURAL_PERSON = n2.NON_NATURAL_PERSON
AND n1.Type > n2.type
WHERE
n2.type IS NULL
Please see this fiddle. If Types are not literally sorted, change this line:
AND n1.Type > n2.type
with this:
AND FIELD(n1.Type, 'TypeA', 'TypeB', 'TypeC') >
FIELD(n2.type, 'TypeA', 'TypeB', 'TypeC')
MySQL FIELD(str, str1, str2, ...) function returns the index (position) of str in the str1, str2, ... list, and 0 if str is not found. You want to get the "first" record, ordered by type, for every NON_NATURAL_PERSON. There are multiple ways to get this info, I chose a self join:
ON n1.NON_NATURAL_PERSON = n2.NON_NATURAL_PERSON
AND n1.Type > n2.type -- or filed function
with the WHERE condition:
WHERE n2.type IS NULL
this will return all rows where the join didn't succeed - the join won't succeed when there is not n2.type that is less than n1.type - it will return the first record.
Edit
If you want a platform independent solution, avoiding the creation of new tables, you could use CASE WHEN, just change
AND n1.Type > n2.Type
with
AND
CASE
WHEN n1.Type='TypeA' THEN 1
WHEN n1.Type='TypeB' THEN 2
WHEN n1.Type='TypeC' THEN 3
END
>
CASE
WHEN n2.Type='TypeA' THEN 1
WHEN n2.Type='TypeB' THEN 2
WHEN n2.Type='TypeC' THEN 3
END
There is a piece of information missing. You say:
Always join name of typeA only if exists. If not, join name of typeB. If neither exists join name of typeC.
But you do not indicate why you prefer typeA over typeB. This information is not included in your data.
In the answer of #fthiella, either lexicographical is assumed, or an arbitrary order is given using FIELD. This is also the reason why two joins with the table nnp_name is necessary.
You can solve this problem by adding a table name_type (id, name, order) and changing the type column to contain the id. This will allow you to add the missing information in a clean way.
With an additional join with this new table, you will be able get the preferred nnp_name for each row.