how can I get specific column with duplicated name via Doctrine ORM?
I'm working on a project using custom engine that is made in Zend. The problem is
I got duplicated column names in 2 tables (c_naslovi and c_sportovi)
Can I do column rename maybe? How can I do it?
I'm new in doctrine, sry on n00b question :)
$q = new Doctrine_RawSql();
$q->select("{p.*}, {n.*}, {np.*}, {sp.*}")
->from("c_ponude p LEFT JOIN c_naslovi n ON p.NaslovID = n.NaslovID
LEFT JOIN c_nasloviprijevodi np ON np.NaslovID = n.NaslovID
LEFT JOIN c_sportovi sp ON n.SportID = sp.SportID")
->where("p.DatumVrijemeOdigravanja > NOW()")
->andWhere("(p.IndikatorPonude = 'P' OR p.IndikatorPonude = 'H')")
->andWhere("p.KoeficijentZbroj > 0")
->andWhere("p.BrojPonude = ?", array($offerId))
->orderby("p.RedniBrojRazrade")
->addComponent("p", "cPonude p")
->addComponent("n", "p.cNaslovi n")
->addComponent("np", "n.cNasloviprijevodi np")
->addComponent("sp", "n.cSportovi sp");
$offer = $q->execute();
If I understand your question correctly, You can solve this by adding aliases, but Doctrine uses it's own aliases for the query.
So it will automatically rename the duplicate columns. Something like:
c_naslovi.duplicate_column as c_0
c_sportovi.duplicate_column as s_0
Related
I am trying to convert this query:
SELECT
pdd.pedinte_id, pdd.data, pdd.situacao as Situacao, pdd.valor_total, pdd.qtd_etiquetas,
(
SELECT count(pdi.envio_id)
FROM pedinte_item pdi
INNER JOIN envios env ON
pdi.envio_id = env.envio_id
WHERE
pdi.pedinte_id = pdd.pedinte_id AND
env.Situacao = 2
) AS TemErros
FROM pedinte pdd
left join user usr on
usr.user_id = pdd.user_id
WHERE pdd.user_id IS NOT NULL AND pdd.pedinte_id IS NOT NULL;
to CakePhp:
removed code, maybe very wrong.
Without success.
I have 4 tables:
pedinte (pdd)
pedinte_item (pdi)
envios (env)
user (usr)
pedinte > pedinte_item > envios (count)
Cant believe, harder to do the query builder than the mysql code.
(This does not address the CakePHP question, but too long for a Comment)
(Subqueries are not always "bad".)
These indexes may help performance:
usr: INDEX(user_id)
pdi: INDEX(pedinte_id, envio_id)
env: INDEX(Situacao, envio_id)
When adding a composite index, DROP index(es) with the same leading columns.
That is, when you have both INDEX(a) and INDEX(a,b), toss the former.
I have some trouble when I Joining 3 tables, I use mysqli procedural. here's my query..
$select = $connection->conn->query('SELECT * FROM master_beli, supplier, karyawan WHERE supplier.id_supplier = master_beli.id_supplier AND karyawan.id_karyawan = master_beli.id_karyawan');
After that I viewing with this code
while($fetchData = $select->fetch_array()){
echo $fetchData['id_karyawan'].'<br>';
}
I don't know where the problem is, because I use this query a few months ago and it's worked, but now isn't work..
Could be your issue is related to the ambiguity of the column name id_karyawan present in two tables try use an explicit alias or a explict column naming eg :
$select = $connection->conn->query('SELECT master_beli.id_karyawan
FROM master_beli
INNER JOIN supplier ON supplier.id_supplier = master_beli.id_supplier
INNER JOIN karyawan ON karyawan.id_karyawan = master_beli.id_karyawan');
and as suggested in the code above you should use explicit join sintax ..for better readibilty
(the use of implict join sintax is not more promoted in sql)
SELECT master_beli.id_supplier,master_beli.id_karyawan
FROM master_beli
join supplier on supplier.id_supplier = master_beli.id_supplier
join karyawan on karyawan.id_karyawan = master_beli.id_karyawan;
it work on mysql
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????!!!!
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.
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.