My SQL query is returning duplicate results - php

I have an annoying problem that I cannot get past.
I have a photograph database broken up into two tables:
Table 1 (snaps) consists of four columns:
'photoid', 'filename', 'location', 'created'
Table 2 (befter) which displays the photos in pairs consists of
'ppairid', 'beforeid', 'afterid', 'description'
Table 2 displays the photo pairs, as beforeid and afterid use the unique photoid INT from table 1. All quite simple it would seem.
BUT one of the queries that I have come up with (by location) duplicates if the location of beforeid and afterid are the same. So for example:-
SELECT *
FROM befter, snaps
WHERE (snaps.photoid = befter.beforeid OR snaps.photoid = befter.afterid)
AND snaps.location = 'oxford'
is fine when the photo location is different but not if they're the same. I've tried adding DISTINCT etc but I can't figure it out.
Any ideas please?
P

Use two left joins:
select b.*, sb.*, sa.*
from befter b left join
snaps sb
on sb.photoid = b.beforeid and sb.location = 'oxford' left join
snaps sa
on sa.photoid = b.afterid and sa.location = 'oxford'
where sb.photoid is not null or sa.photoid is not null;
This includes both the before and after snaps in the result set.

You have to tell the SQL statement what you are fetching from the given tables. If you take an * on two tables, then you will get duplicate results.
Try this:
SELECT
snaps.photoid, snaps.filename, snaps.location, snaps.created, befter.ppairid,
befter.beforeid, befter.afterid, befter.description
FROM
befter
INNER JOIN
snaps
ON
snaps.photoid = befter.ppairid
WHERE
snaps.location='oxford'
AND
(snaps.photoid = befter.beforeid OR snaps.photoid = befter.afterid)

Related

5 checkboxes in SQL-Generated HTML table, How to make them only apply for that row?

First post here, sorry for formatting.
So, I have a MySQL Database, that I am returning data from in the form of an HTML table.
Query follows.
select p.patient_id, pd.fname, pd.lname, p.drug, p.start_date, p.end_date,
lo1.title as form, p.quantity, p.size, lo2.title as units, lo3.title as
route, lo4.title as 'interval' from prescriptions as p
inner join patient_data pd on p.patient_id = pd.pid
inner join list_options lo1 on p.form = lo1.option_id
inner join list_options lo2 on p.unit = lo2.option_id
inner join list_options lo3 on p.route = lo3.option_id
inner join list_options lo4 on p.interval = lo4.option_id
where p.patient_id = '106'
and lo1.list_id = 'drug_form'
/* and lo1.option_id = '1' */
and lo2.list_id = 'drug_units'
/* and lo2.option_id = '1' */
and lo3.list_id = 'drug_route'
and lo4.list_id = 'drug_interval'
Which produces a table like this:
[SQL Table] -Redacted due to no reputation-
My Question is: I need to have 5 checkboxes per row returned in the HTML table (And yes, for the record, it is meant to be a dynamic query for entry of a different patient_id), but if I do a checkbox array using PHP, it returns the same five checkboxes to each row. How can we solve this? Please ask for further clarification, I understand I may need to provide more data.
UPDATE: Picture of intended HTML Table, returned by PHP
HTML Table
UPDATE 2: PHP Script: https://pastebin.com/8mWh1xfQ

Need to run 3 queries that use the result of the previous query.. on PHP

I am creating a website that will show specific records to some folks in the company here. I am using PHP, HTML and MYSLQ to create it.
This is the basic layout I am trying to present:
It is an html website, and each row has collapsible rows on 2 levels:
Reference Number > Entries > Invoices
So in this logic, a Reference Number can have one or multiple Entries and an Entry can have one or multiple Invoices.
The html table is a no brainer, the problem is to feed the data into the website.
How I made it work...
Using PHP I created a procedure that first queries the database for the References, then I do a while loop to go through the References and then using the reference number I query the Entries and do a while loop to go through them and use the Entry Number to query for the Invoices.
Now, I am an amateur coder, but I do know that putting the query inside a while loop is extremely bad practice. So I am struggling to making this work properly.
Furthermore, I want this to work by using stored procedures so that all the querying happens on mysql server, rather than on the client side.
Here are the queries:
Query 1 (Main level):
SELECT
oc.sNumCajaTrailer AS Caja,
oc.dFechaCruce AS FechaSalida,
t.sNombre AS Transportista,
tfc.sCveTrafico AS Reference <--- This is the key for the next query
FROM cb_detalle_orden_carga doc
JOIN cb_orden_carga oc ON doc.iConsecutivoOrdenCarga = oc.iConsecutivo
JOIN cu_transfer t ON oc.sCveTransfer = t.sCveTransfer
JOIN cb_trafico tfc ON doc.sCveTrafico = tfc.sCveTrafico
JOIN cu_cliente cte ON tfc.sCveCliente = cte.sCveCliente
WHERE
(oc.dFechaCruce IS NULL OR oc.dFechaCruce IN (fechaSalida))
AND tfc.sCveCliente = 'CLT_6840' AND (doc.sCveTrafico LIKE '%N16%' OR doc.sCveTrafico LIKE '%N17%')
GROUP BY doc.sCveTrafico
Query 2 (FirstSubLevel)
SELECT b.sCveEntradaBodega AS Entry, <----- This is the key for next query
cp.sNombreProveedor AS NombreProveedor,
b.dFechaIngreso AS FechaIngreso,
b.iCantidadBultos AS Bultos,
cb.sDescripcion AS TipoBultos
FROM cb_bulto b
JOIN cb_entrada_bodega eb ON b.sCveEntradaBodega = eb.sCveEntradaBodega
JOIN cu_cliente_proveedor cp ON eb.sCveProveedor = cp.sCveProveedor
AND cp.sCveCliente = eb.sCveCliente
JOIN cb_detalle_orden_carga doc ON b.iConsecutivo = doc.iConsecutivoBulto
JOIN cb_orden_carga oc ON doc.iConsecutivoOrdenCarga = oc.iConsecutivo
JOIN ct_bulto cb ON b.sCveBulto = cb.sCveBulto
WHERE b.sCveTrafico = Reference
Query 3 (Second and last sublevel)
SELECT
f.sNumero AS numFactura,
eb.sNumTalon AS numGuia,
pf.sCveClienteProveedorProducto AS numParte,
pf.iCantidadProducto AS cantidadProducto,
f.sNumeroPedido AS numOrden,
b.iCantidadBultos AS cantidadBultos,
tb.sDescripcion AS tipoBultos
FROM
cb_bulto b
JOIN cb_relacion_remesa_banco_facturas rbf ON b.iConsecutivo = rbf.iConsecutivoBulto
JOIN cb_factura f ON rbf.iFolio = f.iFolio
JOIN cb_entrada_bodega eb ON b.sCveEntradaBodega = eb.sCveEntradaBodega
JOIN cb_producto_factura pf ON f.iFolio = pf.iFolio
JOIN ct_bulto tb ON b.sCveBulto = tb.sCveBulto
WHERE
b.sCveEntradaBodega = Entry
Any ideas????!!!!

mysql How To join 2 column value into 2 column value

I have two tables with columns as follows:
khs (id, year, program, codemk)
subjects (id, year, program, codemk,namemk, tm, pr, lp)
I want to have a result containing:
codemk, namemk, tm, pr, lp
Note: Fields year, program and codemk in khs table each is not unique also in subjects table. But combine the 3 value of those fields make a unique value.
I tried this:
SELECT khs.id khs.codemk, subjects.namemk, subjects.tm, subject.pr, subjects.lp
FROM khs
RIGHT JOIN subjects
ON khs.year + khs.program +khs.codemk = subjects.year + subjects.program + subjects.codemk;
but the result for tm, pr and lp is not what I expected. What am I missing? Sorry I am new to MySQL and how do i create it to new table view.
Thanks in advance.
Maybe this:
SELECT khs.id khs.codemk, subjects.namemk, subjects.tm, subject.pr, subjects.lp
FROM khs
RIGHT JOIN subjects
ON khs.year=subjects.year, khs.program =subjects.program, khs.codemk = subjects.codemk;
But not sure if that is what you asked, otherwise:
SELECT khs.id khs.codemk, subjects.namemk, subjects.tm, subject.pr, subjects.lp
FROM khs
RIGHT JOIN subjects
ON CONCAT(khs.year,khs.program, khs.codemk) = CONCAT(subjects.year, subjects.program, subjects.codemk);
Why use a join? Why not try something like this:
SELECT codemk,namemk,tm,pr,lp
FROM khs,subjects
WHERE khs.year = subjects.year
I am not sure what is your result expectetions (could you provide it please? as well as samples of data tables) but you can try for now:
SELECT khs.id khs.codemk, subjects.namemk, subjects.tm, subject.pr, subjects.lp
FROM khs
INNER JOIN subjects
ON khs.year = subjects.year
AND khs.program = subjects.program
AND khs.codemk = subjects.codemk;

Query two tables for different/separate values

I have two tables:
task
id name dueDate completed projectID
project
id name dueDate completed
I need to query both tables for rows with the same data. I tried doing a sample statement just looking for rows with completed=0, but never got any results. I think it has to do with using OR instead of AND, but it's just a little above my level right now...Any ideas?
TO CLARIFY, I'm not looking for duplicate rows, I'm looking for 'all tasks and projects with completed = 0'
The query is:
SELECT * FROM "task" t, "project" p WHERE t.dueDate = "2012-08-17" OR p.dueDate = "2012-08-17" AND t.completed = 0 OR p.completed = 0
I did manage to get one of the answers' code to work, however I realized that my entire app was written to talk to one table, and that it would be much easier to just combine the task and project table and use an isProject column to differentiate projects from tasks. This also adds the ability to nest projects inside of projects, because projects will now have a projectID column as well.
In the end, KISS prevails...
Thanks for all the help! I will mark the answer that worked, even though I won't be using it.
Try using parenthesis.
SELECT * FROM "task" t, "project" p WHERE (t.dueDate = "2012-08-17" OR p.dueDate = "2012-08-17") AND (t.completed = 0 OR p.completed = 0)
If You want only values matches from both tables with completed=0 from dueDate='2012-08-17':
You can use join to bound that tables results into one.
Inner join will return only results which matches on both sides.
So You can use it to match them in both tables by it and then filter for Your wanted value by classic where:
select * from task t inner join project p on t.dueDate = p.dueDate and t.completed = p.completed
where t.dueDate = '2012-08-17' and t.completed = 0
Try this instead:
SELECT dueDate, completed
FROM task AS t
WHERE (dueDate = "2012-08-17" AND completed = 0)
UNION ALL
SELECT dueDate, completed
FROM project AS p
WHERE (dueDate = "2012-08-17" AND completed = 0)
This should give you all records from each table where dueDate = "2012-08-17" and completed = 0.

Returning data from multiple tables in one query even if secondary tables do not apply

I have an issue getting data from three tables, which I want to return using one query.
I've done this before using a query something like this one:
$query = mysql_query("SELECT
maintable.`id`,
maintable.`somedata`,
maintable.`subtable1_id`,
subtable1.`somedata`,
subtable1.`subtable2_id`,
subtable2.`somedata`
FROM
`maintable` maintable,
`subtable1` subtable1,
`subtable2` subtable2
WHERE
maintable.`somedata` = 'some_search' AND
subtable1.`id` = maintable.`subtable1_id` AND
subtable2.`id` = subtable1.`subtable2_id`
")or die(mysql_error());
The problem this time is that the extra details might not actually apply. I need to return all results that match some_search in maintable, even if there is no subtable1_id specified.
I need something that will go along the lines of
WHERE
maintable.`somedata` = 'some_search'
AND IF maintable.`subtable1_id` IS NOT NULL (
WHERE subtable1.`id` = maintable.`subtable1_id` AND
subtable2.`id` = subtable1.`subtable2_id`
)
As you will probably guess, I am not an advanced mysql user! Try as I might, I cannot get the syntax right, and I have had no luck searching for solutions on the web.
Any help much appreciated!
It seems like the basic distinction you're looking for is between an INNER JOIN and a LEFT JOIN in MySQL.
An INNER JOIN will require a reference between the two tables. There must be a match on both sides for the row to be returned.
A LEFT JOIN will return matches in both rows, like an INNER, but it will also returns rows from your primary table even if no rows match in your secondary tables -- their fields will be NULL.
You can find example syntax in the docs.
If I got this right, you need to use MySQL LEFT JOIN. Try this:
SELECT
m.id,
m.somedata,
m.subtable1_id,
s1.somedata,
s1.subtable2_id,
s2.somedata
FROM
maintable m
LEFT JOIN
subtable1 s1
ON
m.subtable1_id = s1.id
LEFT JOIN
subtable2 s2
ON
s1.subtable2_id = s2.id
WHERE
m.somedata = 'some search'
This will return the data of maintable even if there's no equivalent data in subtable1 or 2 OR data of maintable and subtable1 if there's no equivalent data in subtable2.
How about this:
WHERE
maintable.`somedata` = 'some_search'
AND (maintable.`subtable1_id` IS NULL OR (
subtable1.`id` = maintable.`subtable1_id` AND
subtable2.`id` = subtable1.`subtable2_id` )
)
Keep in mind that this will result in a cross product of subtable1 and subtable2 with maintable when subtable1_id is NULL.

Categories